package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"webdemo/src/zinx/utils"
	"webdemo/src/zinx/zinterface"
)

/**
封包、拆包
*/

type DataPack struct{}

func NewDataPack() *DataPack {
	return &DataPack{}
}

func (d *DataPack) GetHeadLen() uint32 {
	// DataLen uint32 (4字节)，ID uint32 (4字节)
	return 8
}

func (d *DataPack) Pack(msg zinterface.IMessage) ([]byte, error) {
	dataBuf := bytes.NewBuffer([]byte{})
	// 1 将datalen 写入buf
	err := binary.Write(dataBuf, binary.LittleEndian, msg.GetDataLen())
	if err != nil {
		return nil, err
	}
	// 2 dataId
	err = binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgId())
	if err != nil {
		return nil, err
	}
	// 3 data数据
	err = binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgData())
	if err != nil {
		return nil, err
	}
	return dataBuf.Bytes(), nil
}

func (d *DataPack) Unpack(binaryData []byte) (zinterface.IMessage, error) {
	// 按写入顺序读取
	dataBuf := bytes.NewReader(binaryData)
	// 解压信息
	msg := &Message{}
	err := binary.Read(dataBuf, binary.LittleEndian, &msg.DataLen)
	if err != nil {
		return nil, err
	}

	err = binary.Read(dataBuf, binary.LittleEndian, &msg.Id)
	if err != nil {
		return nil, err
	}

	if utils.GlobalObj.MaxPackageSize > 0 && msg.DataLen > utils.GlobalObj.MaxPackageSize {
		return nil, errors.New("data too large")
	}

	return msg, nil

}
